<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="queryParams.username" placeholder="输入用户名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="输入昵称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="动态内容" prop="content">
        <el-input v-model="queryParams.content" placeholder="请输入动态内容" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="审核状态" prop="status" style="width: 220px;">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
          <el-option v-for="dict in sys_dynamic_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="点赞数" prop="likeCount">
        <el-input v-model="queryParams.likeCount" placeholder="请输入动态点赞数" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="评论数" prop="commentCount">
        <el-input v-model="queryParams.commentCount" placeholder="请输入评论数" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="浏览量" prop="views">
        <el-input v-model="queryParams.views" placeholder="请输入浏览量" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="时间范围" style="width: 308px">
        <el-date-picker v-model="dateRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
          format="YYYY-MM-DD HH:mm:ss" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[
            new Date(2000, 0, 1, 0, 0, 0),
            new Date(2000, 0, 1, 23, 59, 59)
          ]" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['dynamic:dynamic:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dynamic:dynamic:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dynamic:dynamic:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['dynamic:dynamic:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dynamicList" @selection-change="handleSelectionChange" stripe>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="动态编号" align="center" prop="dynamicId" />
      <el-table-column label="用户名" align="center" prop="username"></el-table-column>
      <el-table-column label="昵称" align="center" prop="nickname"></el-table-column>
      <el-table-column label="动态内容" align="center" prop="content" show-overflow-tooltip>
        <!--    可以看见也使用到插槽语法      -->
        <template #default="scope">
          <!--    使用v-html属性，可以渲染字符串是html标签  -->
          <div v-html="scope.row.content"></div>
        </template>
      </el-table-column>
      <el-table-column label="内容图片" align="center" prop="images" width="100" show-overflow-tooltip>
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="点赞数" align="center" prop="likeCount" />
      <el-table-column label="评论数" align="center" prop="commentCount" />
      <el-table-column label="浏览量" align="center" prop="views" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_dynamic_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" show-overflow-tooltip>
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['dynamic:dynamic:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['dynamic:dynamic:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改动态管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="dynamicRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发布人" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入发布人id，关联tb_user表" @blur="exit" />
        </el-form-item>
        <el-form-item label="动态内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="内容图片" prop="images">
          <image-upload v-model="form.images" />
        </el-form-item>
        <el-form-item label="审核状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option v-for="dict in sys_dynamic_status" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" :disabled="!form.userId">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dynamic">
import { listDynamic, getDynamic, delDynamic, addDynamic, updateDynamic } from "@/api/dynamic/dynamic"
import request from '@/utils/request'
import { getUsers } from "@/api/users/users"


const { proxy } = getCurrentInstance()

// 添加字典数据
const { sys_dynamic_status } = proxy.useDict("sys_dynamic_status")

const dynamicList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRange = ref([])
// const userKeyword = ref('')

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    content: null,
    images: null,
    likeCount: null,
    commentCount: null,
    views: null,
    status: null,
    publishTime: null,
    beginTime: null, // Add for start of date range
    endTime: null,
    nickname: null,
    username: null
  },
  rules: {
    status: [
      { required: true, message: "审核状态不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询动态管理列表 */
function getList() {
  loading.value = true;
  listDynamic(queryParams.value).then(response => {
    // 确保状态是字符串类型
    dynamicList.value = response.rows
    total.value = response.total || 0;
  }).finally(() => {
    loading.value = false;
  });
}

function exit() {
  const userId = form.value.userId;
  // 空值检查
  if (!userId) {
    console.log("用户ID为空");
    return;
  }
  // 转换为数字并检查
  const numUserId = Number(userId);
  if (isNaN(numUserId)) {
    proxy.$modal.msgError("用户ID必须是数字");
    form.value.userId = ""; // 清空非数字输入
    return;
  }
  getUsers(form.value.userId).then(res => {
    if (res.data === undefined) {
      proxy.$modal.msgError("用户不存在")
      form.value.userId = ""
    }
  })
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    dynamicId: null,
    userId: null,
    content: null,
    images: null,
    likeCount: null,
    commentCount: null,
    views: null,
    status: "0", // 默认设置为通过状态
    publishTime: null,
    username: null,
    nickname: null
  }
  proxy.resetForm("dynamicRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  console.log(dateRange.value)
  // 设置日期范围参数
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.beginTime = dateRange.value[0];
    queryParams.value.endTime = `${dateRange.value[1]} 23:59:59`;
  } else {
    queryParams.value.beginTime = null;
    queryParams.value.endTime = null;
  }
  console.log(queryParams.value)
  queryParams.value.pageNum = 1
  getList()
}

// 添加专用的状态修改方法
function changeDynamicStatus(dynamicId, status) {
  return request({
    url: '/dynamic/dynamic/changeStatus',
    method: 'put',
    data: {
      dynamicId: dynamicId,
      status: status
    }
  })
}

// /** 审核状态修改 */
// function handleStatusChange(row) {
//   const originalStatus = row.status;
//   const text = row.status === "0" ? "通过" : "拒绝";
//   proxy.$modal.confirm(`确认要将动态 "${row.content?.substring(0, 20)}..." ${text}审核吗?`)
//     .then(() => {
//       return changeDynamicStatus(row.dynamicId, row.status);
//     })
//     .then(() => {
//       proxy.$modal.msgSuccess(`${text}成功`);
//     })
//     .catch((error) => {
//       console.error("状态更新失败:", error);
//       row.status = originalStatus; // 回滚状态
//       proxy.$modal.msgError("状态更新失败");
//     });
// }


/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [] // Reset date range
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.dynamicId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加动态管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _dynamicId = row.dynamicId || ids.value
  getDynamic(_dynamicId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改动态管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dynamicRef"].validate(valid => {
    if (valid) {
      if (form.value.dynamicId != null) {
        updateDynamic(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDynamic(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _dynamicIds = row.dynamicId || ids.value
  proxy.$modal.confirm('是否确认删除动态管理编号为"' + _dynamicIds + '"的数据项？').then(function () {
    return delDynamic(_dynamicIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('dynamic/dynamic/export', {
    ...queryParams.value
  }, `dynamic_${new Date().getTime()}.xlsx`)
}

getList()
</script>
